package com.zhx.learn.quartz.controller;

import com.zhx.learn.quartz.entity.SaasJob;
import com.zhx.learn.quartz.res.SaasJobDao;
import com.zhx.learn.quartz.schedule.ScheduleUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 *describe: 
 *
 *@author zhanghaixuan
 *@date 2018/10/30
 **/
@RequestMapping("/v1")
@RestController
public class QuzrtzController {

	@Autowired
	private Scheduler scheduler;

	@Autowired
	private SaasJobDao saasJobDao;

	/**
	 * 项目启动时，初始化定时器
	 */
	@PostConstruct
	public void init()
	{
		List<SaasJob> saasJobs = saasJobDao.findAll();
		for (SaasJob job : saasJobs){
			CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, job.getUid());
			// 如果不存在，则创建
			if (cronTrigger == null){
				ScheduleUtils.createScheduleJob(scheduler, job);
			} else{
				ScheduleUtils.updateScheduleJob(scheduler, job);
			}
		}
	}
}
